<?php

class CropsPlugin {
    var $ld;
    var $xmlsOb;
    var $bot;
    function CropsPlugin()
    {
      include 'codebase-php/GetSettingsFromXml.php';
      $this->xmlsOb=new xmlsOb();
      //$this->xmlsOb->GenerateFnames();
      $this->ld = new LocalData();
    }
	// ==========================================================================
    function GetOptionsByTypeName($name)
    {
        $arr = "";
        //$xmlsOb=new xmlsOb();
        $res="";
        foreach ($this->xmlsOb->gsXML->items->item as $item)

        {
          if ((string)$item['type'] == $name)	  
		  $arr[] = (string)$item['name'];
        }		
        natcasesort($arr);
        foreach ($arr as $item)
        {

          //$res=$res."<option>".$item. " ".$xmlsOb->GetCashCost($item)." (".$xmlsOb->GetgrowTime($item).")</option>";
		  $res=$res."<option>".$item. " ".$this->xmlsOb->GetCashCost($item)."</option>";
        }
        return $res;
    }
    // ==========================================================================
	function GetGreenhouses()
    {
      $ret = '<table class="table1">';
      $ret .= "<tr><td>Greenhouse</td><td>ID</td><td>Contract</td><td>Started</td><td>State</td><td></td><td></td></tr>";
        $res=$this->ld->GetSelect("select * from objects");
        foreach ($res as $val){
            $v=(string)$val[1];
            $obj=unserialize(base64_decode($v));
            if($obj['className'] == "GreenHouse")

            {
              if((string)$obj['mechanicData']['greenHouseStorage']['item']['state'] == "grown") { $state = "Ready";}
			  else
			  if((string)$obj['mechanicData']['greenHouseStorage']['item']['state'] == "plowed") { $state = "Plowed";}
			  else
			  if((string)$obj['mechanicData']['greenHouseStorage']['item']['state'] == "withered") { $state = "Withered";}
			  else{ $state = "Growing";}
                                          //  String  rio   Number  1292943824000                                                                                     String Reference  grown
             $ret .= "<tr><td>".$obj['itemName']."</td><td>".$obj['id']."</td><td>".$obj['mechanicData']['greenHouseStorage']['item']['contractName']."</td><td>".$this->ld->nicetime($obj['mechanicData']['greenHouseStorage']['item']['plantTime']/1000)."</td><td>".$state."</td><td></td><td></td></tr>";

            }
        }
      $ret .= "</table>";
      return $ret;

    }
    // ==========================================================================
	    function GetXMLtime($time)
    {
      $tmptime = (string)$time*(23/24); // now the time is in days.
      $tmptime = $tmptime * 24 * 60 ; // now time is in min.
      if($tmptime >= 0 && $tmptime < 60){ $tmptime= round($tmptime, 1)." Min."; }
      if($tmptime >= 60 && $tmptime < 3600){ $tmptime= round($tmptime/60, 1)." Hour"; }
      if($tmptime >= 3660 && $tmptime < 86400){ $tmptime= round($tmptime/60/24, 1)." Day"; }
      $nicetime = $tmptime;
      return $nicetime;
    }
    // ==========================================================================
    function GetForm() {
        $fln = 'tmp_dir\fnames.txt';
        $fl = fopen($fln, 'r');
        $fnames = unserialize(fread($fl, filesize($fln)));
        fclose($fl);
        //print_r($fnames);
        foreach($fnames['crops'] as $crop)
			
		{
            $options = $options . '<option value="' . $crop['name'] . '">' . $crop['fname'] . '</option>';
        }
        //==========================================================================
      global $imagePath;
      $imagePath = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));
    $PlVersion = (array)$this->ld->GetPlVersion('cropsplugin');
    $settings = (array) $this->ld->GetPlSettings('cropsplugin');
    echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="ru">
    <head>
        <title>Crops</title>
        <script src="..\..\codebase-php\jquery-1.4.2.min.js"></script>
        <script src="..\..\codebase-php\jquery.json-2.2.min.js"></script>
        <link href="helpers/plugin.css" rel="stylesheet" type="text/css">
		   <style>
             #maint{ font-size: 10pt; width: 850px; padding: 0px; }
           </style>
		   
		<script language="JavaScript" type="text/javascript">
          <!--
          var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);
          function addOption(theSel, theText, theValue)
          {
            var newOpt = new Option(theText, theValue);
            var selLength = theSel.length;
            theSel.options[selLength] = newOpt;
          }

          function deleteOption(theSel, theIndex)
          {
            var selLength = theSel.length;
            if(selLength>0)
            {
              theSel.options[theIndex] = null;
            }
          }

          function moveOptions(theSelFrom, theSelTo)
          {
            var selLength = theSelFrom.length;
            var selectedText = new Array();
            var selectedValues = new Array();
            var selectedCount = 0;
            var i;
            // Find the selected Options in reverse order and delete them from the from Select.
            for(i=selLength-1; i>=0; i--)
            {
              if(theSelFrom.options[i].selected)
              {
                selectedText[selectedCount] = theSelFrom.options[i].text;
                selectedValues[selectedCount] = theSelFrom.options[i].value;
                deleteOption(theSelFrom, i);
                selectedCount++;
              }
            }

            // Add the selected text/values in reverse order.
            // This will add the Options to the TO Select
            // in the same order as they were in the FROM Select.
            for(i=selectedCount-1; i>=0; i--)
            {
              addOption(theSelTo, selectedText[i], selectedValues[i]);
            }

            if(NS4) history.go(0);
          }
          //-->
        </script>
        <script>
        //==============================================================
        window.reload = function(){
                var l=window.location.toString();
                var indx=l.indexOf(\'?\');
                window.location=l.slice(0, indx)+"?action=refresh&tmp="+Math.random();
        }
        //==============================================================
            $(document).ready(function(){
                //==============================================================
                window.settings=eval(' . json_encode($this->ld->GetPlSettings('cropsplugin')) . ');

                //console.debug(window.settings);

                if ((window.settings!==null) && (window.settings!==undefined))
                {
				  $("#contractIN_").val(window.settings.contractIN_);
				
                  $(":checkbox").each(function()
                  {
                    if(window.settings[$(this).attr("id")]==true)
                    { $(this).attr("checked", true); }
                    else
                    { $(this).attr("checked", false); }
                  });
                  var slist=window.settings["seedlist"];
                  if ((slist!=undefined) && (slist.length>0))
                  {
                    for(var $i=0;$i<slist.length; $i++)
                    {
                      var curr=slist[$i];
                      var tmp=curr.split("|");
                      var cnt=tmp[1];
                      var name=tmp[0];
                      if ((cnt!=undefined) && (name!=undefined))
                      {
                        $("#seedlist").append(\'<option value=\' + name+ " | "+cnt + \'>\' + name+ " | "+cnt + \'</option>\');
                      }
                    }
                  }
                }
                window.seedlist=new Array();
                $("#add").click(function()
                {
                  var tmp=$("#croplist").val()+ " | " + $("#count").val();
                  $("#seedlist").append("<option value=\'"+tmp+"\'>"+tmp+"</option>");
                  return false;
                });
                //==============================================================
                $("#remove").click(function(){
                    $("#seedlist option:selected").remove();
                    return false;
                });
                //==============================================================
                $("#up").click(function(){
                    var val=$("#seedlist option:selected").text();
                    var f1val=$("#seedlist").children();
                    var fval=$(f1val[0]).text();
                    var prev=$("#seedlist option:selected").prev();
                    if (val!=fval){
                        $("#seedlist option:selected").remove();
                        prev.before("<option value=\'"+val+"\' selected>"+val+"</option>");
                    }
                });
                //==============================================================
                $("#down").click(function(){
                    var val=$("#seedlist option:selected").text();
                    var fval=$("#seedlist").children().last().text();
                    var prev=$("#seedlist option:selected").next();
                    if (val!=fval){
                        $("#seedlist option:selected").remove();
                        prev.after("<option value=\'"+val+"\' selected>"+val+"</option>");
                    }
                });
                //==============================================================
                $("#btn_save").click(function(){
                var req=new Object();
                var i=0;
                    $("#seedlist").children().each(function(){
                        window.seedlist.push($(this).text());
                    });

                                        $(":checkbox").each(function(){
                                            var par=$(this).attr("id");
                                            req[par]=$(this).attr("checked");
                                        });

                    req.collectCropsData=new Array();
                    $("#collectCropsData option").each(function(){
                          req.collectCropsData.push($(this).attr("id")+""+$(this).text());
                     });
                    req["seedlist"]=window.seedlist;
		            req["contractIN_"]=$("#contractIN_").val();
					
					req.collectgreenHouseIN=new Array();
                    $("#collectgreenHouseIN option").each(
                       function(){
                         var par=$(this).val();
                         req.collectgreenHouseIN.push(par);
                         //req.collectgreenHouseIN.push($(this).attr("id")+""+$(this).text());
                       });
					
                    data=$.toJSON(req);
                    var l=window.location.toString();
                    var indx=l.indexOf(\'?\');
                    var nurl=l.slice(0, indx)+"?action=save&tmp="+Math.random();
                    $.post(nurl, data);


                    return false;
                });
            });
        </script>
        </head>
        <body>
        <form >
		  <table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#DAA520">
			  <tr height="23">
               <td><hr><h1>CROPS (by 12Christiaan)</h1>
               <h2>REVAMPED by Tonycell, Updated by Chaos & BQ (11.05.2012)</h2><hr></td>
              </tr>
			 </table>
			  <br>
            </div>
          
		  <br>
		    <b>Options</b>:
            <br>
            <input type="checkbox" id="ALLbonus">Streak Bonus<br><br>';
		    //=========== Greenhouse Grassroots ===============================================================
	 echo '  <table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#ff0066">
             <tr height="23">
              <td><h3>Greenhouses</h3></td>
             </tr>
            </table>';		
			
     echo '<br>
	         <table>
             <tr>
              <td>
                <input type="checkbox" id="collectgreenHouse">Harvest Greenhouses?<br>
                <input type="checkbox" id="seedgreenHouse">Seed Crops?
                &nbsp;&nbsp;Contracts:
                <select id="contractIN_">'.$this->GetOptionsByTypeName("plot_contract").'</select> <br><br>
			    <b>Options</b>:
                <br>
                <input type="checkbox" id="clearGreenHouse">Clear withered Greenhouses<br></td>
              <td width="100%"><img src="'.$imagePath.'assets/greenhouse/mun_greenhouse_longterm_2_icon.png" name="pictures" ></td>
             </tr>
            </table>
	         <br>
           Avaliable Grassroots:<br>';
      if(!isset($settings['collectgreenHouseIN'])) $settings['collectgreenHouseIN'] = array();
      $resNOT="";
      $resN = array();
      $resIN="";
      $resI = array();
      $objects = $this->ld->GetObjects();
      foreach ($objects as $key=>$item)
      {
        if ((string)$item['className'] == "GreenHouse")

        {
          $found = "N";
          if (in_array((string)$item['id'],$settings['collectgreenHouseIN'])) {$found = "Y";}
          if($found == "Y" )
          { $resI[$item['id']] = (string)$item['itemName'];}
          else
          { $resN[$item['id']] = (string)$item['itemName'];}
        }
      }
      natcasesort($resI);
      natcasesort($resN);
      foreach ($resI as $id=>$item)
      {
        $resIN .= '<option value="'.$id.'">'.$item." ($id)</option>";
      }
      foreach ($resN as $id=>$item)
      {
        $resNOT .= '<option value="'.$id.'">'.$item." ($id)</option>";
      }
       echo  '&nbsp;&nbsp;
            <table class="table1">
              <th>Do NOT harvest/seed</th><th></th><th>Do harvest/seed</th></tr>
                <tr>
                 <td>
                   <select name="sel3" size="10" multiple="multiple">';
       echo $resNOT;
       echo '      </select>
                 </td>
                 <td align="center" valign="middle">
                  <input type="button" value="--&gt;"onclick="moveOptions(this.form.sel3, this.form.sel4);" /><br />
                  <input type="button" value="&lt;--"onclick="moveOptions(this.form.sel4, this.form.sel3);" />
                 </td>
                 <td>
                  <select name="sel4" size="10" multiple="multiple" id="collectgreenHouseIN">';
       echo $resIN;
	  
	  
	  echo '   </select>
              </td>
             </tr>
           </table>';
      echo  '<hr>Below here you have some more information on your Greenhouses.<br>';
	  echo $this->GetGreenhouses();
   
			//=================================================================================================
	  echo ' <br>
             <table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#ff0066">
             <tr height="23">
              <td><h3>Planting</h3></td>
             </tr>
            </table>
            <table style="margin-top: 10px; margin-left: 2px;">
              <tr>
               <td style="width: 500px;" valign="top">
                Select crop: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Count:
                <br>
                <select id="croplist" name="croplist" style="width: 190px;">'.$this->GetOptionsByTypeName("plot_contract").'</select>
                <input type="text" size="20" name="count" id="count" value="0" style="width: 50px;">
                <br>
                <br>
                <button id="add" style="width:50px">+</button>
                <button id="remove" style="width:50px">-</button>
                <button id="up" style="width:50px">up</button>
                <button id="down" style="width:50px">down</button>
                <br>
                <select name="seedlist" id="seedlist" size=10  style="width:250px"></select>
               </td>
              </tr>
            </table>
            <br>
            <table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#ff0066">
             <tr height="23">
              <td><h3>Harvesting</h3></td>
             </tr>
            </table>
            <input type="checkbox" id="collectcrop">Harvest Crop?<br>
            <br>
            <b>Options</b>:
            <br>
            <input id="NoHarvestIfFull" type="checkbox"> Stop Harvest if total goods is 90% full.<br>
            <input id="clearWithered" type="checkbox"> Clear withered crops.<br>
            <br>
						Select the Crop you like to collect:';
        if(!isset( $settings['collectCropsData'])) $settings['collectCropsData'] = array();
        $resNOT="";
		$resN=array();
        $resIN="";
		$resI=array();
        foreach ($this->xmlsOb->gsXML->items->item as $item)
        {
          if ((string)$item['type'] == "plot_contract" && (string)$item['name'] != "plot_no_wither")
            {			
              $found = "N";
              foreach($settings['collectCropsData'] as $item2) { if((string)$item['name'] == $item2) {$found = "Y";} }
              if($found == "Y" )
              { $resI[] = (string)$item['name'];}
              else
              { $resN[] = (string)$item['name'];}
            }
        }
      natcasesort($resI);
      natcasesort($resN);
      foreach ($resI as $item)
      {
        $resIN .= "<option>".$item."</option>";
      }
      foreach ($resN as $item)
      {
        $resNOT .= "<option>".$item."</option>";
      }
       echo  '&nbsp;&nbsp;
            <table class="table1">
              <th>Do NOT collect</th><th></th><th>Do collect</th></tr>
                <tr>
                 <td>
                   <select name="sel1" size="10" multiple="multiple">';
       echo $resNOT;
       echo '      </select>
                 </td>
                 <td align="center" valign="middle">
                  <input type="button" value="--&gt;"onclick="moveOptions(this.form.sel1, this.form.sel2);" /><br />
                  <input type="button" value="&lt;--"onclick="moveOptions(this.form.sel2, this.form.sel1);" />
                 </td>
                 <td>
                  <select name="sel2" size="10" multiple="multiple" id="collectCropsData">';
       echo $resIN;
       echo '     </select>
                 </td>
                </tr>
         </table>
			   <br>
         <hr>
         <div width="100%" align="center">
          <button id="btn_save" style="color:white;background-color:#13a89e;border-width:1px;border-style:solid; ">&nbsp; Save Settings&nbsp;</button>
         </div>
         <hr>
         <table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#ff0066">
          <tr height="23">
           <td><h3>Plot List</h3></td>
          </tr>
         </table>
         <br>
         <table style="width: 200px; background-color: white;border-width: 1px;">
          <tr>
           <td><b>ID</b></td>
           <td><b>Contract</b></td>
           <td><b>State</b></td>
          </tr>';


         $Objects = $this->ld->GetObjects();
         $i = 0;
         $a = 0; $b = 0; $c = 0; $d = 0;
         foreach ($Objects as $obj)
         {
           if($obj['className']=="Plot")
           {
             $color = "";
             if ($obj['state']=="grown"){ $color = '#228B22'; $a++;} //forestgreen
             else
             if ($obj['state']=="withered"){ $color = '#FF4500'; $b++;} //orange red
             else
             if ($obj['state']=="plowed"){ $color = '#FFA07A'; $c++;} //light salmon
             else
             if ($obj['state']=="planted"){ $color = 'white'; $d++;}

             echo '<tr>';
             echo '<td style="background-color:'.$color.'">'.$obj['id'].'</td>';
             echo '<td style="background-color:'.$color.'">'.$obj['contractName'].'</td>';
             echo '<td style="background-color:'.$color.'">'.$obj['state'].'</td>';
             //echo '<td style="background-color:'.$color.'">'.$this->ld->nicetime($obj['plantTime']/1000).'</td>';
             echo '</tr>';
             $i++;
           }
         }
     echo'
         </table>
         <h2>Grown: '.$a.'</h2>
         <h2>Withered: '.$b.'</h2>
         <h2>Plowed: '.$c.'</h2>
         <h2>Planted: '.$d.'</h2>
         <h1>Total: '.$i.' plots</h1>
        </form>
        </body>
        </html>
        ';
    }
}

?>